package org.sean.framework.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @param <T> create at 2014年5月21日 上午10:44:02
 * @author Sean.xie
 */
public abstract class GSONType<T> {
    public static final GSONType<Object> EMPTY_JSON_TYPE = new GSONType<Object>() {
    };
    private final Type type;

    /**
     * Constructs a new type literal. Derives represented class from type
     * parameter.
     * Clients create an empty anonymous subclass. Doing so embeds the type
     * parameter in the anonymous class's type hierarchy so we can reconstitute
     * it at runtime despite erasure.
     */
    protected GSONType() {
        this.type = getSuperclassTypeParameter();
    }

    /**
     * Returns the type from super class's type parameter
     */
    Type getSuperclassTypeParameter() {

        Class<?> cls = getClass();
        while (!(cls.getGenericSuperclass() instanceof ParameterizedType)) {
            cls = cls.getSuperclass();
        }
        return ((ParameterizedType) cls.getGenericSuperclass()).getActualTypeArguments()[0];
    }

    /**
     * Gets underlying {@code Type} instance.
     *
     * @return Type
     */
    public final Type getType() {
        return type;
    }

}
